﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DGSFramework;
using System.Web.Security;
using System.IO;
using CodeCarvings.Piczard.Web;
using CodeCarvings.Piczard;
using System.Web.Services;
using System.Xml.Linq;
using CodeCarvings.Piczard.Filters.Watermarks;
using System.Web.Script.Services;

namespace Framework.WebmasterTool.Articles
{
    public partial class ArticleAdd : System.Web.UI.Page
    {
        DGSFrameworkEntities entity = new DGSFrameworkEntities();

        protected void Page_Load(object sender, EventArgs e)
        {
            //txtRealeaseDate.Attributes.Add("readonly", "readonly");
            //txtExpireDate.Attributes.Add("readonly", "readonly");
            siuImage.ImageRemove += new EventHandler(siuImage_ImageRemove);
            siuImage.ImageUpload += new SimpleImageUpload.ImageUploadEventHandler(siuImage_ImageUpload);
            if (!IsPostBack)
            {
                CheckPermission();
                CallCkeditors();
                //CleanImageUploadTemp();
                CallImageUpload();
                LoadCateDDL();
                LoadArticleDetails();
            }
        }

        public void CheckPermission()
        {
            MembershipUser someUser = Membership.GetUser();
            if (someUser == null)
            {
                Response.Redirect(Globals.ApplicationPath + "LoginAdmin/Default.aspx");
            }
            bool flag = false;
            var user = entity.aspnet_Users.Where(us => us.UserName == someUser.UserName).FirstOrDefault();
            user.aspnet_Roles.Load();
            var rolesForUser = user.aspnet_Roles.ToList();
            foreach (var item in rolesForUser)
            {
                var permission = entity.udv_Permissions.Where(ps => ps.RoleId == item.RoleId).FirstOrDefault();
                if (permission.Article.Value == true)
                {
                    flag = true;
                }
            }
            if (flag == false)
            {
                lblPermissionMessage.Visible = true;
                Panel1.Visible = false;
            }
        }

        public void CallCkeditors()
        {
            Globals.CallCKFinder(txtBody);
            Globals.CallCKFinder(txtBody_en);
        }

        void siuImage_ImageRemove(object sender, EventArgs e)
        {
            chkWatermarkImage.Enabled = true;
        }

        void siuImage_ImageUpload(object sender, SimpleImageUpload.ImageUploadEventArgs args)
        {
            chkWatermarkImage.Enabled = false;
        }

        public void CleanImageUploadTemp()
        {
            foreach (var file in Directory.GetFiles(Server.MapPath(ConfigPaths.Path_ImageUploadTemp_Folder_MapPath)))
            {
                File.Delete(file);
            }
        }

        public void ImageUpload(SimpleImageUpload ctrImageUpload)
        {
            ctrImageUpload.ImageBackColorApplyMode = PictureTrimmerImageBackColorApplyMode.DoNotApply;
            ctrImageUpload.CropConstraint = new FreeCropConstraint();
            ctrImageUpload.PreviewFilter = new FixedResizeConstraint(200, 200, System.Drawing.Color.Black);
            ctrImageUpload.Text_BrowseButton = "Upload ảnh";
            ctrImageUpload.Text_CancelUploadButton = "Huỷ";
            ctrImageUpload.Text_EditButton = "Sửa ảnh";
            ctrImageUpload.Text_RemoveButton = "Xoá ảnh";
        }

        public void CallImageUpload()
        {
            ImageUpload(siuImage);
        }

        public void LoadCateDDL()
        {
            string levels = "|---";
            string spaces = "&nbsp;";
            List<udv_Categories> allCate = entity.udv_Categories.ToList();
            List<udv_Categories> cateBannerParent = allCate.Where(ca => ca.ParentID == ConfigPaths.Category_Article_ID).ToList();
            foreach (var item in cateBannerParent)
            {
                ddlCategories.Items.Add(new ListItem(item.Title, item.CateID.ToString()));
                LoadSubCateDDL(ref allCate, item.CateID, ref spaces, levels);
            }
        }

        public void LoadSubCateDDL(ref List<udv_Categories> allCate, int cateParentID, ref string spaces, string levels)
        {
            List<udv_Categories> subCateBanner = allCate.Where(ca => ca.ParentID == cateParentID).ToList();
            foreach (var item in subCateBanner)
            {
                ddlCategories.Items.Add(new ListItem(HttpUtility.HtmlDecode(spaces) + levels + item.Title, item.CateID.ToString()));
                if (entity.udv_Categories.Where(ca => ca.ParentID == item.CateID).ToList().Count > 0)
                {
                    spaces += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
                    LoadSubCateDDL(ref allCate, item.CateID, ref spaces, levels);
                }
            }
            if (spaces.Length > 6)
                spaces = spaces.Substring(0, spaces.Length - 36);
        }

        public void LoadArticleDetails()
        {
            if (Request.QueryString["ArticleID"] != null)
            {
                int articleID;
                int.TryParse(Request.QueryString["ArticleID"], out articleID);
                var articleByID = entity.udv_Articles.Include("udv_Categories").Where(ar => ar.ArticleID == articleID).FirstOrDefault();
                if (articleByID != null)
                {
                    LoadListImageArticle(articleByID.ArticleID);
                    ddlCategories.SelectedValue = articleByID.udv_Categories.CateID.ToString();
                    txtTitle.Text = articleByID.Title.Trim();
                    txtTitle_en.Text = articleByID.Title_en.Trim();
                    txtAbstract.Text = articleByID.Abstract;
                    txtAbstract_en.Text = articleByID.Abstract_en;
                    txtMetaDescription.Text = articleByID.MetaDescription.Trim();
                    txtMetaKeywords.Text = articleByID.MetaKeywords.Trim();
                    txtMetaTitle.Text = articleByID.MetaTitle.Trim();
                    txtMetaOrther.Text = HttpUtility.HtmlDecode(articleByID.MetaOrther.Trim());
                    if (articleByID.ImageUrl != null && articleByID.ImageUrl.Trim() != "")
                    {
                        string sourceImageFilePath = ConfigPaths.Path_ImageArticle_Folder_MapPath + articleByID.ImageUrl;
                        siuImage.LoadImageFromFileSystem(Server.MapPath(sourceImageFilePath));
                        chkWatermarkImage.Enabled = false;
                    }
                    //load relate
                    txtRelateTop.Text = GetRelatesToString("top", articleByID);
                    txtRelateBottom.Text = GetRelatesToString("bottom", articleByID);
                    txtRelateProduct.Text = GetRelatesToString("product", articleByID);
                    //load tag
                    articleByID.udv_Tag.Load();
                    txtTags.Text = GetTagsToString(articleByID.udv_Tag.ToList());

                    txtImageAlt.Text = articleByID.ImageAlt.Trim();
                    txtBody.Text = articleByID.Body;
                    txtBody_en.Text = articleByID.Body_en;
                    txtDisplayOrder.Text = articleByID.DisplayOrder.Value.ToString();
                    txtRealeaseDate.Text = String.Format("{0:dd/MM/yyyy hh:mm:ss tt}", articleByID.ReleaseDate);
                    txtExpireDate.Text = String.Format("{0:dd/MM/yyyy hh:mm:ss tt}", articleByID.ExpireDate);
                    chkCommentsEnable.Checked = articleByID.CommentsEnabled.Value;
                    chkApprovedComments.Checked = articleByID.ApprovedComments.Value;
                    chkOnlyForMember.Checked = articleByID.OnlyForMembers.Value;
                    chkIsApproved.Checked = articleByID.IsApproved.Value;
                    chkConfirmOrder.Checked = articleByID.ConfirmOrder.Value;
                    chkTopNews.Checked = articleByID.StatusID == 1 ? true : false;
                    lblAddedDate.Text = String.Format("{0:dd/MM/yyyy HH:mm:ss tt}", articleByID.AddedDate);
                    lblAddedBy.Text = articleByID.AddedBy;
                    lblUpdatedDate.Text = String.Format("{0:dd/MM/yyyy HH:mm:ss tt}", articleByID.UpdatedDate);
                    lblUpdatedBy.Text = articleByID.UpdatedBy;
                    lblTotalRating.Text = articleByID.TotalRating.ToString();
                    lblViewCount.Text = articleByID.ViewCount.ToString();
                    lbllink.Text = ConfigPaths.Domain_Url + articleByID.UrlRewrite + DGSFramework.Globals.GetUrlRewriteExtension();
                }
                else
                {
                    Response.Redirect("Default.aspx");
                }
            }
        }

        public void LoadListImageArticle(int articleID)
        {
            List<udv_ArticleImages> listImageArticle = entity.udv_ArticleImages.Where(ia => ia.udv_Articles.ArticleID == articleID).ToList();
            dtlImage.DataSource = listImageArticle;
            dtlImage.DataBind();
        }

        [WebMethod]
        public static void DeleteImageArticle(string ImageID)
        {
            DGSFrameworkEntities entity = new DGSFrameworkEntities();
            int imageID = int.Parse(ImageID);
            udv_ArticleImages imageArticle = entity.udv_ArticleImages.Where(ia => ia.ImageID == imageID).FirstOrDefault();
            if (imageArticle != null)
            {
                Globals.DelelteFile(HttpContext.Current.Server.MapPath(ConfigPaths.Path_ImageArticle_Folder_MapPath + imageArticle.ImageUrl));
                entity.DeleteObject(imageArticle);
                entity.SaveChanges();
            }
        }

        [WebMethod]
        public static void EditAttributeImageArticle(string ImageID, string NewValue, string Attribute)
        {
            DGSFrameworkEntities entity = new DGSFrameworkEntities();
            int imageID = int.Parse(ImageID);
            udv_ArticleImages imageArticle = entity.udv_ArticleImages.Where(ia => ia.ImageID == imageID).FirstOrDefault();
            string value = NewValue;
            string attribute = Attribute;
            if (imageArticle != null)
            {
                if (attribute.Trim() == "title")
                {
                    imageArticle.Title = value;
                }
                else if (attribute.Trim() == "title_en")
                {
                    imageArticle.Title_en = value;
                }
                else if (attribute.Trim() == "alt")
                {
                    imageArticle.ImageAlt = value;
                }
                entity.SaveChanges();
            }
        }

        protected void chkWatermarkImage_CheckedChanged(object sender, EventArgs e)
        {
            if (chkWatermarkImage.Checked == true && siuImage.HasImage == false)
            {
                XDocument xDocWatermark = XDocument.Load(Server.MapPath(ConfigPaths.Path_Watermark_Xml));
                XElement xEImage = xDocWatermark.Descendants("img").FirstOrDefault();
                siuImage.PostProcessingFilter = new ImageWatermark(Server.MapPath(ConfigPaths.Path_ImageUpload_Folder_MapPath + xEImage.Value), System.Drawing.ContentAlignment.BottomRight);
            }
            else if (chkWatermarkImage.Checked == false && siuImage.HasImage == false)
            {
                siuImage.PostProcessingFilter = null;
            }
        }

        public List<string> UploadAndGetImageName()
        {
            List<string> strFileName = new List<string>();
            HttpFileCollection hfc = Request.Files;
            if (hfc.Count > 0)
            {
                for (int i = 0; i < hfc.Count; i++)
                {
                    HttpPostedFile hpf = hfc[i];
                    if (hpf.FileName.Trim() != "")
                    {
                        string strFileNameTemp = Globals.GetFileName(hpf.FileName);
                        strFileName.Add(strFileNameTemp);
                        if (chkWatermarkImage2.Checked == false)
                            hpf.SaveAs(Server.MapPath(ConfigPaths.Path_ImageArticle_Folder_MapPath + strFileNameTemp));
                        else
                        {
                            XDocument xDocWatermark = XDocument.Load(Server.MapPath(ConfigPaths.Path_Watermark_Xml));
                            XElement xEImage = xDocWatermark.Descendants("img").FirstOrDefault();
                            Globals.CreateWatermark(hpf, Server.MapPath(ConfigPaths.Path_ImageArticle_Folder_MapPath + strFileNameTemp), Server.MapPath(ConfigPaths.Path_ImageUpload_Folder_MapPath + xEImage.Value));
                        }
                    }
                }
            }
            return strFileName;
        }

        public List<string> GetImageTitle()
        {
            List<string> listTitle = new List<string>();
            for (int i = 0; i < int.Parse(hdfNumImage.Value); i++)
            {
                if (Request.Form["Title" + i.ToString()] != null)
                {
                    listTitle.Add(Request.Form["Title" + i.ToString()].Trim());
                }
            }
            return listTitle;
        }

        public List<string> GetImageTitle_en()
        {
            List<string> listTitle = new List<string>();
            for (int i = 0; i < int.Parse(hdfNumImage.Value); i++)
            {
                if (Request.Form["Title_en" + i.ToString()] != null)
                {
                    listTitle.Add(Request.Form["Title_en" + i.ToString()].Trim());
                }
            }
            return listTitle;
        }

        public List<string> GetImageAlt()
        {
            List<string> listAlt = new List<string>();
            for (int i = 0; i < int.Parse(hdfNumImage.Value); i++)
            {
                if (Request.Form["Alt" + i.ToString()] != null)
                {
                    listAlt.Add(Request.Form["Alt" + i.ToString()].Trim());
                }
            }
            return listAlt;
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            int cateID = 0;
            try
            {
                cateID = int.Parse(ddlCategories.SelectedValue);
            }
            catch
            {
                lblMsg.Text = "Chưa chọn danh mục cho bài viết";
            }
            udv_Categories cateForArticle = entity.udv_Categories.Where(ca => ca.CateID == cateID).FirstOrDefault();
            int countChildCate = entity.udv_Categories.Where(ca => ca.ParentID == cateID).ToList().Count;
            if (countChildCate > 0)
            {
                lblMsg.Text = "Danh mục này có danh mục con nên không thể có bài viết";
                lblMsg.ForeColor = System.Drawing.Color.Red;
                return;
            }
            List<string> listImageNameUpload = UploadAndGetImageName();
            List<string> listImageTitle = new List<string>();
            List<string> listImageTitle_en = new List<string>();
            List<string> listImageAlt = new List<string>();
            if (listImageNameUpload.Count > 0)
            {
                listImageTitle = GetImageTitle();
                listImageTitle_en = GetImageTitle_en();
                listImageAlt = GetImageAlt();
            }
            if (Request.QueryString["ArticleID"] == null)
            {
                udv_Articles articleInsert = new udv_Articles();
                articleInsert.Title = txtTitle.Text.Trim();
                articleInsert.Title_en = txtTitle_en.Text.Trim();
                articleInsert.Abstract = txtAbstract.Text;
                articleInsert.Abstract_en = txtAbstract_en.Text;
                articleInsert.Body = txtBody.Text;
                articleInsert.Body_en = txtBody_en.Text;
                articleInsert.udv_Categories = cateForArticle;
                if (siuImage.HasImage == true)
                {
                    string fileNameImage = Globals.GetFileName(siuImage.SourceImageClientFileName);
                    siuImage.SaveProcessedImageToFileSystem(ConfigPaths.Path_ImageArticle_Folder + fileNameImage);
                    articleInsert.ImageUrl = fileNameImage;
                }
                else
                {
                    articleInsert.ImageUrl = "";
                }
                articleInsert.ImageAlt = txtImageAlt.Text.Trim();
                if (txtRealeaseDate.Text.Trim() != "")
                {
                    articleInsert.ReleaseDate = DateTime.ParseExact(txtRealeaseDate.Text.Trim(), "dd/MM/yyyy hh:mm:ss tt", null);
                }
                if (txtExpireDate.Text.Trim() != "")
                {
                    articleInsert.ExpireDate = DateTime.ParseExact(txtExpireDate.Text.Trim(), "dd/MM/yyyy hh:mm:ss tt", null);
                }
                articleInsert.StatusID = chkTopNews.Checked == true ? 1 : 0;
                articleInsert.ConfirmOrder = chkConfirmOrder.Checked;
                articleInsert.CommentsEnabled = chkCommentsEnable.Checked;
                articleInsert.ApprovedComments = chkApprovedComments.Checked;
                articleInsert.OnlyForMembers = chkOnlyForMember.Checked;
                articleInsert.TotalRating = 0;
                articleInsert.ViewCount = 0;
                articleInsert.DisplayOrder = int.Parse(txtDisplayOrder.Text);
                articleInsert.AddedDate = DateTime.Now;
                articleInsert.AddedBy = Membership.GetUser().UserName;
                articleInsert.UpdatedDate = DateTime.Now;
                articleInsert.UpdatedBy = Membership.GetUser().UserName;
                articleInsert.IsApproved = chkIsApproved.Checked;
                articleInsert.MetaDescription = txtMetaDescription.Text.Trim();
                articleInsert.MetaKeywords = txtMetaKeywords.Text.Trim();
                articleInsert.MetaTitle = txtMetaTitle.Text.Trim();
                articleInsert.MetaOrther = HttpUtility.HtmlEncode(txtMetaOrther.Text.Trim());
                entity.AddToudv_Articles(articleInsert);
                entity.SaveChanges();
                // add relate to article
                AddRelateToArticle(txtRelateTop.Text, articleInsert, "top");
                AddRelateToArticle(txtRelateBottom.Text, articleInsert, "bottom");
                AddRelateToArticle(txtRelateProduct.Text, articleInsert, "product");
                // add tag to article
                AddTagToArticle(txtTags.Text, articleInsert);
                if (listImageNameUpload.Count > 0)
                {
                    for (int i = 0; i < listImageNameUpload.Count; i++)
                    {
                        udv_ArticleImages imageArticle = new udv_ArticleImages();
                        imageArticle.udv_Articles = articleInsert;
                        imageArticle.ImageUrl = listImageNameUpload[i];
                        imageArticle.ImageAlt = listImageAlt[i];
                        imageArticle.Title = listImageTitle[i];
                        imageArticle.Title_en = listImageTitle_en[i];
                        imageArticle.Description = "";
                        imageArticle.Description_en = "";
                        imageArticle.AddedDate = DateTime.Now;
                        entity.AddToudv_ArticleImages(imageArticle);
                        entity.SaveChanges();
                    }
                }
                string urlRewriteArticle = Globals.CreateUrlRewriteArticle(ref entity, articleInsert.ArticleID, true);
                articleInsert.UrlRewrite = urlRewriteArticle;
                entity.SaveChanges();
                Globals.CreateROR("~/ror.xml", urlRewriteArticle + DGSFramework.Globals.GetUrlRewriteExtension(), articleInsert.Title, articleInsert.MetaDescription);
                Globals.CreateSiteMap("~/sitemap.xml", urlRewriteArticle + DGSFramework.Globals.GetUrlRewriteExtension());
                Globals.CreateUrlList("~/urllist.txt", urlRewriteArticle + DGSFramework.Globals.GetUrlRewriteExtension());
                //data cache
                Cache.Remove("Article");
                //create db log
                CreateDBLog(articleInsert.ArticleID, cateForArticle.CateID, TypeAction.Insert, "Tạo bài viết: " + articleInsert.Title, 
                    articleInsert.Abstract, articleInsert.Body, articleInsert.ReleaseDate != null ? string.Format("{0:dd/MM/yyyy} HH:mm:ss", articleInsert.ReleaseDate) : "",
                    articleInsert.ExpireDate != null ? string.Format("{0:dd/MM/yyyy} HH:mm:ss", articleInsert.ExpireDate) : "", articleInsert.IsApproved.Value.ToString(), 
                    articleInsert.StatusID.Value.ToString(), articleInsert.MetaDescription, articleInsert.MetaKeywords);
                //clear outputcache
                HttpResponse.RemoveOutputCacheItem("/Default.aspx");
                HttpResponse.RemoveOutputCacheItem("/Articles.aspx");
                //redirect page
                Response.Redirect("Default.aspx");
            }
            else
            {
                int articleID;
                int.TryParse(Request.QueryString["ArticleID"].ToString(), out articleID);
                udv_Articles articleUpdate = entity.udv_Articles.Where(ar => ar.ArticleID == articleID).FirstOrDefault();
                if (articleUpdate != null)
                {
                    string urlRewriteArticleOld = Globals.CreateUrlRewriteArticle(ref entity, articleUpdate.ArticleID, true);
                    string urlRewriteArticleNew;
                    string oldTitle = articleUpdate.Title;
                    articleUpdate.Title = txtTitle.Text.Trim();
                    articleUpdate.Title_en = txtTitle_en.Text.Trim();
                    articleUpdate.Abstract = txtAbstract.Text;
                    articleUpdate.Abstract_en = txtAbstract_en.Text;
                    articleUpdate.Body = txtBody.Text;
                    articleUpdate.Body_en = txtBody_en.Text;
                    articleUpdate.udv_Categories = cateForArticle;
                    if (siuImage.HasNewImage == true)
                    {
                        Globals.DelelteFile(Server.MapPath(ConfigPaths.Path_ImageArticle_Folder_MapPath + articleUpdate.ImageUrl));
                        string fileNameImage = Globals.GetFileName(siuImage.SourceImageClientFileName);
                        siuImage.SaveProcessedImageToFileSystem(ConfigPaths.Path_ImageArticle_Folder + fileNameImage);
                        articleUpdate.ImageUrl = fileNameImage;
                    }
                    else if (siuImage.HasImage == false)
                    {
                        Globals.DelelteFile(Server.MapPath(ConfigPaths.Path_ImageArticle_Folder_MapPath + articleUpdate.ImageUrl));
                        articleUpdate.ImageUrl = "";
                    }
                    articleUpdate.ImageAlt = txtImageAlt.Text.Trim();
                    if (txtRealeaseDate.Text.Trim() != "")
                    {
                        articleUpdate.ReleaseDate = DateTime.ParseExact(txtRealeaseDate.Text.Trim(), "dd/MM/yyyy hh:mm:ss tt", null);
                    }
                    else
                    {
                        articleUpdate.ReleaseDate = null;
                    }
                    if (txtExpireDate.Text.Trim() != "")
                    {
                        articleUpdate.ExpireDate = DateTime.ParseExact(txtExpireDate.Text.Trim(), "dd/MM/yyyy hh:mm:ss tt", null);
                    }
                    else
                    {
                        articleUpdate.ExpireDate = null;
                    }
                    articleUpdate.StatusID = chkTopNews.Checked == true ? 1 : 0;
                    articleUpdate.ConfirmOrder = chkConfirmOrder.Checked;
                    articleUpdate.CommentsEnabled = chkCommentsEnable.Checked;
                    articleUpdate.ApprovedComments = chkApprovedComments.Checked;
                    articleUpdate.OnlyForMembers = chkOnlyForMember.Checked;
                    articleUpdate.DisplayOrder = int.Parse(txtDisplayOrder.Text);
                    articleUpdate.UpdatedDate = DateTime.Now;
                    articleUpdate.UpdatedBy = Membership.GetUser().UserName;
                    articleUpdate.IsApproved = chkIsApproved.Checked;
                    articleUpdate.MetaDescription = txtMetaDescription.Text.Trim();
                    articleUpdate.MetaKeywords = txtMetaKeywords.Text.Trim();
                    articleUpdate.MetaTitle = txtMetaTitle.Text.Trim();
                    articleUpdate.MetaOrther = HttpUtility.HtmlEncode(txtMetaOrther.Text.Trim());
                    entity.SaveChanges();
                    // add tag to article
                    AddRelateToArticle(txtRelateTop.Text, articleUpdate, "top");
                    AddRelateToArticle(txtRelateBottom.Text, articleUpdate, "bottom");
                    AddRelateToArticle(txtRelateProduct.Text, articleUpdate, "product");
                    // add tag to article
                    AddTagToArticle(txtTags.Text, articleUpdate);
                    if (listImageNameUpload.Count > 0)
                    {
                        for (int i = 0; i < listImageNameUpload.Count; i++)
                        {
                            udv_ArticleImages imageArticle = new udv_ArticleImages();
                            imageArticle.udv_Articles = articleUpdate;
                            imageArticle.ImageUrl = listImageNameUpload[i];
                            imageArticle.ImageAlt = listImageAlt[i];
                            imageArticle.Title = listImageTitle[i];
                            imageArticle.Title_en = listImageTitle_en[i];
                            imageArticle.Description = "";
                            imageArticle.Description_en = "";
                            imageArticle.AddedDate = DateTime.Now;
                            entity.AddToudv_ArticleImages(imageArticle);
                            entity.SaveChanges();
                        }
                    }
                    urlRewriteArticleNew = Globals.CreateUrlRewriteArticle(ref entity, articleUpdate.ArticleID, true);
                    articleUpdate.UrlRewrite = urlRewriteArticleNew;
                    entity.SaveChanges();
                    Globals.UpdateROR("~/ror.xml", urlRewriteArticleOld + DGSFramework.Globals.GetUrlRewriteExtension(), urlRewriteArticleNew + DGSFramework.Globals.GetUrlRewriteExtension(), articleUpdate.Title, articleUpdate.MetaDescription);
                    Globals.UpdateSiteMap("~/sitemap.xml", urlRewriteArticleOld + DGSFramework.Globals.GetUrlRewriteExtension(), urlRewriteArticleNew + DGSFramework.Globals.GetUrlRewriteExtension());
                    Globals.UpdateUrlList("~/urllist.txt", urlRewriteArticleOld + DGSFramework.Globals.GetUrlRewriteExtension(), urlRewriteArticleNew + DGSFramework.Globals.GetUrlRewriteExtension());
                    //data cache
                    Cache.Remove("Article");
                    //create db log
                    CreateDBLog(articleUpdate.ArticleID, cateForArticle.CateID, TypeAction.Update, "Cập nhật bài viết: " + oldTitle + " - " + articleUpdate.Title, articleUpdate.Abstract, articleUpdate.Body, articleUpdate.ReleaseDate != null ? string.Format("{0:dd/MM/yyyy} HH:mm:ss", articleUpdate.ReleaseDate) : "",
                        articleUpdate.ExpireDate != null ? string.Format("{0:dd/MM/yyyy} HH:mm:ss", articleUpdate.ExpireDate) : "", articleUpdate.IsApproved.Value.ToString(), articleUpdate.StatusID.Value.ToString(), articleUpdate.MetaDescription, articleUpdate.MetaKeywords);
                    //output cache
                    string key = "/ArticleDetails.aspx?ArticleID=" + articleUpdate.ArticleID.ToString();
                    Cache.Remove(key);
                    HttpResponse.RemoveOutputCacheItem("/Default.aspx");
                    HttpResponse.RemoveOutputCacheItem("/Articles.aspx");
                    //redirect page
                    Response.Redirect("Default.aspx");
                }
                else
                {
                    lblMsg.Text = "Bài viết muốn cập nhật không tồn tại";
                    lblMsg.ForeColor = System.Drawing.Color.Red;
                }
            }
        }

        public List<string> ParseRelatesString(string relateString)
        {
            return relateString.Split('~').Select(tg => tg.ToLower().Trim()).Distinct().ToList();
        }

        public string GetRelatesToString(string position, udv_Articles article)
        {
            article.udv_Relate.Load();
            var relateNames = article.udv_Relate.Where(tg => tg.Position.ToLower().Trim() == position.ToLower().Trim()).Select(tg => tg.RelateName);
            return string.Join("~ ", relateNames.ToArray());
        }

        public List<udv_Relate> FindRelatesAddedArticleByNames(List<string> relateNames, string position)
        {
            List<udv_Relate> existingRelates = entity.udv_Relate.ToList().Where(tg => relateNames.Any(tn => tg.RelateName == tn)).ToList();
            foreach (var item in relateNames)
            {
                if (!existingRelates.Any(tg => tg.RelateName == item))
                {
                    int? postID = entity.udv_Articles.Where(ar => ar.Title.ToLower().Trim() == item.ToLower().Trim()).Select(ar => ar.ArticleID).FirstOrDefault();
                    if (postID != null && postID != 0)
                    {
                        udv_Relate newRelate = new udv_Relate { RelateName = item, PostID = postID, Position = position };
                        entity.AddToudv_Relate(newRelate);
                        entity.SaveChanges();
                        existingRelates.Add(newRelate);
                    }
                    else
                    {
                        postID = entity.udv_Products.Where(ar => ar.Title.ToLower().Trim() == item.ToLower().Trim()).Select(ar => ar.ProductID).FirstOrDefault();
                        if (postID != null)
                        {
                            udv_Relate newRelate = new udv_Relate { RelateName = item, PostID = postID, Position = position };
                            entity.AddToudv_Relate(newRelate);
                            entity.SaveChanges();
                            existingRelates.Add(newRelate);
                        }
                    }
                }
            }
            return existingRelates;
        }

        public void AddRelateToArticle(string relateString, udv_Articles article, string position)
        {
            relateString = relateString.Replace("\r\n", "").Replace("\n", "").Replace("\r", "");
            article.udv_Relate.Load();
            article.udv_Relate
                .Where(tg => tg.Position.ToLower().Trim() == position.ToLower().Trim()).ToList()
                .ForEach(tg => entity.DeleteObject(tg));
            entity.SaveChanges();
            List<udv_Relate> relates = string.IsNullOrEmpty(relateString) ? null : FindRelatesAddedArticleByNames(ParseRelatesString(relateString), position);
            if (relates != null && relates.Count != 0)
            {
                relates.ForEach(tg => article.udv_Relate.Add(tg));
            }
            entity.SaveChanges();
        }

        [WebMethodAttribute(), ScriptMethodAttribute()]
        public static string[] GetCompletionTagList(string prefixText, int count, string contextKey)
        {
            DGSFrameworkEntities entity = new DGSFrameworkEntities();
            var listTags = entity.udv_Tag.ToList();
            return (from tg in listTags where tg.TagName.Contains(prefixText) select tg.TagName).Take(count).ToArray();
        }

        public List<string> ParseTagsString(string tagString)
        {
            return tagString.Split(',').Select(tg => tg.ToLower().Trim()).Distinct().ToList();
        }

        public string GetTagsToString(List<udv_Tag> tags)
        {
            var tagNames = tags.Select(tg => tg.TagName);
            return string.Join(", ", tagNames.ToArray());
        }

        public List<udv_Tag> FindTagsAddByNames(List<string> tagNames)
        {
            List<udv_Tag> alltag = entity.udv_Tag.ToList();
            List<udv_Tag> existingTags = alltag.Where(tg => tagNames.Any(tn => tg.TagName == tn)).ToList();
            foreach (var item in tagNames)
            {
                if (!existingTags.Any(tg => tg.TagName == item))
                {
                    udv_Tag newTag = new udv_Tag { TagName = item };
                    entity.AddToudv_Tag(newTag);
                    entity.SaveChanges();
                    existingTags.Add(newTag);
                }
            }
            return existingTags;
        }

        public void AddTagToArticle(string tagString, udv_Articles article)
        {
            article.udv_Tag.Load();
            article.udv_Tag.Clear();
            entity.SaveChanges();
            List<udv_Tag> tags = string.IsNullOrEmpty(tagString) ? null : FindTagsAddByNames(ParseTagsString(tagString));
            if (tags != null && tags.Count != 0)
            {
                tags.ForEach(tg => article.udv_Tag.Add(tg));
            }
            entity.SaveChanges();
        }

        public void CreateDBLog(int? postID, int? postCateID, TypeAction typeAction, string title, string _abstract, string description,
        string releaseDate, string expireDate, string isApproved, string statusID, string metaDescription, string metaKeywords)
        {
            udv_Log log = new udv_Log();
            log.PostID = postID;
            log.PostCateID = postCateID;
            log.TypeAction = (int)typeAction;
            log.Title = title;
            log.Abstract = _abstract;
            log.Description = description;
            log.ReleaseDate = releaseDate;
            log.ExpireDate = expireDate;
            log.IsApproved = isApproved;
            log.StatusID = statusID;
            log.MetaDescription = metaDescription;
            log.MetaKeywords = metaKeywords;
            log.ActionedDate = DateTime.Now;
            log.ActionBy = Membership.GetUser().UserName;
            log.IpAdress = Globals.GetClientIPAddress();

            entity.AddToudv_Log(log);
            entity.SaveChanges();
        }
    }
}